package com.starnet.yarnmonitor.security.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.starnet.yarnmonitor.security.entity.SysRole;
import com.starnet.yarnmonitor.security.entity.SysUserRoleRelation;
import com.starnet.yarnmonitor.security.mapper.SysRoleMapper;
import com.starnet.yarnmonitor.security.mapper.SysUserMapper;
import com.starnet.yarnmonitor.security.mapper.SysUserRoleRelationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class UserUtil {
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysRoleMapper sysRoleMapper;
    @Autowired
    SysUserRoleRelationMapper sysUserRoleRelationMapper;
    private static UserUtil userUtil;


    @PostConstruct
    public void init() {
        userUtil = this;
        userUtil.sysUserMapper = this.sysUserMapper;
        userUtil.sysRoleMapper = this.sysRoleMapper;
        userUtil.sysUserRoleRelationMapper = this.sysUserRoleRelationMapper;
    }


    public static int getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();
        String account = user.getUsername();
        int id = userUtil.sysUserMapper.selectByAccount(account).getId();
        return id;
    }

    public static boolean isSuper() {
        //判断是不是超管
        int currentUserId = UserUtil.getCurrentUserId();
        LambdaQueryWrapper<SysRole> sysRoleMapperLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysRoleMapperLambdaQueryWrapper.eq(SysRole::getRoleName, "超级管理员");
        //超管角色id
        Integer superRoleId = userUtil.sysRoleMapper.selectOne(sysRoleMapperLambdaQueryWrapper).getId();
        LambdaQueryWrapper<SysUserRoleRelation> sysUserRoleRelationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserRoleRelationLambdaQueryWrapper.eq(SysUserRoleRelation::getUserId, currentUserId);
        //当前用户的角色id
        Integer currentRoleId = userUtil.sysUserRoleRelationMapper.selectOne(sysUserRoleRelationLambdaQueryWrapper).getRoleId();
        boolean isSuper = currentRoleId == superRoleId;
        return isSuper;
    }
}
